package com.zyw.configuration;

import com.zyw.orm.mybatis.annotation.MyBatisDao;
import com.zyw.orm.support.BaseEntity;
import com.zyw.utils.ResourceUtil;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.support.ResourcePatternResolver;

import javax.sql.DataSource;

/**
 * mybatis spring boot 配置
 *
 * @author zhangyw
 * @date 2017/12/15 14:40
 */
public class MyBatisConfiguration {

    @Bean
    @ConditionalOnBean({DataSource.class, ResourcePatternResolver.class})
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
        SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
        factory.setDataSource(dataSource);
        factory.setConfigLocation(ResourceUtil.getResource("classpath:/com/zyw/orm/mybatis/mybatis-config.xml"));
        factory.setMapperLocations(ResourceUtil.getResources("classpath*:/mappings/**/*.xml"));
        factory.setTypeAliasesPackage("com.zyw");
        factory.setTypeAliasesSuperType(BaseEntity.class);
        return factory.getObject();
    }

    @Bean
    @ConditionalOnBean(SqlSessionFactory.class)
    public MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
        mapperScannerConfigurer.setBasePackage("com.zyw");
        mapperScannerConfigurer.setAnnotationClass(MyBatisDao.class);
        return mapperScannerConfigurer;
    }

    @Bean
    @ConditionalOnBean(SqlSessionFactory.class)
    public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }


}
